package com.tbit.uqbike.task;

import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.service.db.DbService;
import com.tbit.uqbike.service.redis.RedisService;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.pojo.TerOnline;
import com.tbit.uqbike.tergateway.pojo.TerOnlineHis;
import com.tbit.uqbike.util.CollExUtils;
import com.tbit.uqbike.util.Pair;
import com.tbit.uqbike.util.TurnTidToHashSet;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * Created by MyWin on 2018/3/23 0023.
 * 秒级写入任务
 */
public class RedisBatWriterSec implements Runnable {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RedisBatWriterSec.class);

    private TurnTidToHashSet redisTurn = new TurnTidToHashSet();

    @Override
    public void run() {
        writeAllRouteKey();
//        writeAllOnlineItem();
    }

    private void writeAllRouteKey() {
        try {
            HashSet<String> tidSet = TerGatewayData.replaceConnTidSet();
            if (!tidSet.isEmpty()) {
                List<List<Pair<String, List<Pair<String, String>>>>> redisPkgData = CollExUtils.spiltSetToS(tidSet, TerGatewayConfig.iRedisBatSize, redisTurn);
                Date start = new Date();
                RedisService redis = TerGatewayMain.getRedis();
                if (!redisPkgData.isEmpty()) {
                    for (List<Pair<String, List<Pair<String, String>>>> item : redisPkgData) {
                        redis.Hash_BatSetValue(item);
                    }
                }
                Date end = new Date();
                long lMs = end.getTime() - start.getTime();
                logger.info(String.format("Bat Set RouteKey [%d],Use:%d", tidSet.size(), lMs));
            }
        } catch (Exception e) {
            logger.error("writeAllRouteKey", e);
        }
    }

    private void writeAllOnlineItem() {
        DbService db = TerGatewayMain.getDbService();
        try {
            HashMap<String, TerOnline> maps = TerGatewayData.getAllUpdateOnlineItems();
            List<TerOnlineHis> items = TerGatewayData.getAllInsertOnlineItems();

            if (!maps.isEmpty()) {
                List<List<TerOnline>> listLists = CollExUtils.spiltMap(maps, TerGatewayConfig.iDbBatSize);
                for (List<TerOnline> lists : listLists) {
                    db.batUpdateTerOnlines(lists);
                }
            }

            if (!items.isEmpty()) {
                db.batInsertHisTerOnlines(items);
            }

        } catch (Exception e) {
            logger.error("writeAllOnlineItem", e);
        }
    }
}
